Tags: #◇CSMODEL #◇Bayesian Inference #◇Computer Science #◇Data Science #◇Statistical Modeling #◇Python #◇Machine Learning
Module 10: Bayesian Inference
◇Key Concepts
1. Frequentist vs. Bayesian Paradigm
Statistical inference seeks to draw conclusions about population parameters based on sample data. Two main paradigms exist in modern statistics:
| Feature | Frequentist Statistics | Bayesian Statistics |
|---|---|---|
| Definition of Probability | Long-run relative frequency of an event occurring over infinite repetitions of an experiment. | Degree of belief or certainty regarding an event or parameter given available evidence. |
| Parameter View | Fixed, unknown constant. True value is deterministic (e.g., population mean is a single unknown number). | Random variable with a probability distribution. Parameters express uncertainty. |
| Data View | Random variable generated from repeated trials. | Fixed, observed evidence once collected. |
| Prior Information | Disregarded; inference relies solely on current experimental sample data. | Formally integrated into inference via a prior distribution . |
| Stopping Rules / Sample Size | Sensitive to experimental design, sample size , and stopping intentions (can alter p-values). | Immune to stopping rules; inference depends only on observed data via the Likelihood Principle. |
| Interval Estimation | Confidence Interval (e.g., 95% of intervals constructed under repeated sampling contain true ). | Credible Interval (e.g., 95% probability that true lies within the interval). |
[!IMPORTANT]
Key Exam Takeaway: The foundational difference between Frequentist and Bayesian paradigms is that Bayesian statistics treats parameters as random variables with probability distributions, whereas Frequentist statistics treats parameters as fixed, unknown constants.
2. Bayes' Theorem & Its Components
Bayes' Theorem provides the mathematical framework for updating our belief about a parameter or hypothesis upon observing new evidence or data .
Mathematical Formulation
Derived from the conditional probability rule :
Where: Prior Distribution : The probability distribution representing prior strength of belief about parameter before observing the current data . Likelihood : The probability of observing data given a specific parameter value . This represents the data-generating generative model. Marginal Likelihood / Evidence : The total probability of observing the data across all possible parameter values:
Continuous case:
Discrete case:
Acts as a normalizing constant ensuring that the posterior probability density integrates or sums to 1. Posterior Distribution : The updated probability distribution of parameter after observing data .
3. Proportionality & Sequential Updating
Unnormalized Posterior Proportionality
Since the denominator is independent of and serves only to normalize the distribution, Bayesian inference frequently relies on the unnormalized relation:
Sequential Belief Updating
Bayesian learning is dynamic. When data arrives incrementally in batches , the posterior distribution obtained after batch serves as the prior distribution for batch :
[!TIP]
Today's Posterior is Tomorrow's Prior! Updating beliefs sequentially batch-by-batch yields the exact same final posterior distribution as processing all data in a single large combined batch.
4. Conjugate Priors & The Beta-Binomial Model
Definition of Conjugacy
A prior distribution is called a conjugate prior for a likelihood function if the resulting posterior distribution belongs to the exact same algebraic family of distributions as the prior.
Conjugate priors allow analytical, closed-form updates for posterior parameters without needing expensive numerical integration (like MCMC sampling).
The Beta-Binomial Conjugate Pair
The Beta-Binomial pair is the most essential conjugate pair in introductory Bayesian statistics. It models binary outcomes (success/failure, heads/tails, pass/fail).
-
Likelihood (Binomial / Bernoulli):
For independent coin flips yielding heads (successes) given success probability parameter :
-
Prior Distribution (Beta Distribution):
The Beta distribution is parameterized by hyperparameters and :
Hyperparameter interpretation: prior successes, prior failures (pseudo-counts).
Beta Mean:
Beta Variance: -
Posterior Derivation:
Thus, the posterior distribution is also a Beta distribution:
Impact of Data Volume () When sample size is small, the prior parameters heavily pull the posterior mean towards the prior mean. As sample size , the observed data dominates the update, and the posterior mean converges to the Frequentist Maximum Likelihood Estimate (MLE) .
5. Credible Intervals vs. Confidence Intervals
Definition of a 95% Credible Interval
A 95% Credible Interval is an interval in parameter space such that the integrated posterior probability density equals 0.95:
Key Distinctions Bayesian Credible Interval: Direct statement about probability of parameter . "There is a 95% probability that the true parameter lies between and given the observed data." Frequentist Confidence Interval: Indirect statement about sampling repeatability. "If this experiment is repeated infinitely under identical conditions, 95% of the calculated intervals will contain the fixed true parameter ."
Types of Credible Intervals
- Equal-Tailed Credible Interval: Trims equal probability tail areas ( on each tail). Easy to compute using quantiles (
scipy.stats.beta.interval). - Highest Density Interval (HDI): The shortest interval containing 95% of probability density, where every point inside the interval has higher probability density than any point outside.
6. Naive Bayes Classifier
Naive Bayes is a supervised learning classification algorithm built directly on Bayes' Theorem.
Bayes Rule for Classification
Given a feature vector and class labels :
The "Naive" Conditional Independence Assumption
To avoid computing joint likelihoods for high-dimensional feature spaces (which would require massive data), Naive Bayes makes the simplifying assumption that all features are conditionally independent of each other given the class label :
Classification Decision Rule
Since denominator is constant across all candidate classes :
Naive Bayes Variants
- Gaussian Naive Bayes (
GaussianNB): Used for continuous numeric features. Assumes features follow a Normal (Gaussian) distribution within each class:
- Multinomial Naive Bayes (
MultinomialNB): Used for discrete feature counts (e.g., word occurrence frequencies in text document classification). - Bernoulli Naive Bayes (
BernoulliNB): Used for binary indicator features (0 or 1).
Laplace Smoothing (Additive Smoothing)
If a feature value does not appear in training data for class , , causing the entire product to become zero.
Laplace smoothing adds a smoothing constant (typically ) to count estimates:
Where is the size of the feature vocabulary.
◇Python Snippets
1. scipy.stats.beta — Beta Distribution Operations
Computes Beta distribution PDF values, exact theoretical mean, variance, and 95% equal-tailed credible intervals.
import numpy as np
from scipy.stats import beta
# Parameters of posterior Beta(28, 22)
a_param, b_param = 28, 22
# 1. Theoretical mean: E[\theta] = a / (a + b)
mean_val = beta.mean(a_param, b_param)
print(f"Posterior Mean: {mean_val:.4f}") # 28 / (28 + 22) = 0.5600
# 2. Variance & Standard Deviation
var_val = beta.var(a_param, b_param)
std_val = beta.std(a_param, b_param)
print(f"Variance: {var_val:.6f}, Std Dev: {std_val:.4f}")
# 3. 95% Equal-Tailed Credible Interval
# Returns percentiles at 2.5% and 97.5%
ci_lower, ci_upper = beta.interval(0.95, a_param, b_param)
print(f"95% Credible Interval: [{ci_lower:.4f}, {ci_upper:.4f}]")
# 4. Evaluating PDF at specific theta grid point (e.g. theta = 0.5)
pdf_at_05 = beta.pdf(0.5, a_param, b_param)
print(f"PDF at theta=0.5: {pdf_at_05:.4f}")
2. Manual Discrete Bayesian Posterior Calculation (Grid Approximation)
Computes unnormalized posterior by multiplying prior and likelihood on a grid, then normalizes by dividing by the marginal likelihood sum.
import numpy as np
import scipy.stats as stats
# Step 1: Define discrete parameter grid for theta in [0, 1]
theta_grid = np.linspace(0, 1, 101) # 101 points from 0.0 to 1.0
# Step 2: Define Prior distribution (e.g., Uniform prior Beta(1,1) -> flat array)
prior = stats.beta.pdf(theta_grid, 1, 1)
# Normalize prior over grid
prior = prior / np.sum(prior)
# Step 3: Observe Data: N=10 flips, z=8 heads
N = 10
z = 8
# Likelihood function: P(Data | theta) = Binomial PMF
likelihood = stats.binom.pmf(z, n=N, p=theta_grid)
# Step 4: Unnormalized Posterior = Likelihood * Prior
unnormalized_posterior = likelihood * prior
# Step 5: Marginal Likelihood (Evidence P(D)) = sum across grid
evidence = np.sum(unnormalized_posterior)
# Step 6: Normalized Posterior
posterior = unnormalized_posterior / evidence
# Verification: Posterior Mean via expected value sum(theta * posterior)
posterior_mean = np.sum(theta_grid * posterior)
print(f"Marginal Evidence P(D): {evidence:.6e}")
print(f"Grid Posterior Mean: {posterior_mean:.4f}")
3. Full Beta-Binomial Sequential Updating Example
Demonstrates how beliefs update across multiple data batches using scipy.stats.beta.
import numpy as np
from scipy.stats import beta
def report_beta(stage_name, a, b):
mu = beta.mean(a, b)
ci_low, ci_high = beta.interval(0.95, a, b)
print(f"--- {stage_name} ---")
print(f"Beta({a}, {b}) | Mean: {mu:.4f} | 95% Credible Interval: [{ci_low:.4f}, {ci_high:.4f}]\n")
# 1. Initial Prior: Strong belief coin is roughly fair (20 prior heads, 20 prior tails)
a, b = 20, 20
report_beta("Initial Prior", a, b)
# 2. Batch 1: Observe N1=10 flips, z1=8 heads
N1, z1 = 10, 8
a = a + z1
b = b + (N1 - z1)
report_beta("Posterior after Batch 1 (8H/10)", a, b) # Beta(28, 22)
# 3. Batch 2: Observe N2=10 more flips, z2=9 heads
N2, z2 = 10, 9
a = a + z2
b = b + (N2 - z2)
report_beta("Posterior after Batch 2 (9H/10)", a, b) # Beta(37, 23)
4. sklearn.naive_bayes.GaussianNB Classifier
Fits Gaussian Naive Bayes on continuous numeric data and extracts predictions, probabilities, and class parameters.
import numpy as np
from sklearn.naive_bayes import GaussianNB
# Synthetic continuous training data: 4 samples, 2 features
X_train = np.array([
[1.0, 2.1],
[1.5, 1.8],
[5.0, 8.2],
[6.1, 9.0]
])
y_train = np.array([0, 0, 1, 1]) # Class 0 vs Class 1
# 1. Instantiate and Fit Model
gnb = GaussianNB()
gnb.fit(X_train, y_train)
# 2. Test sample
X_test = np.array([[2.0, 3.0]])
# 3. Predict Class and Class Probabilities
pred_class = gnb.predict(X_test)
pred_proba = gnb.predict_proba(X_test)
print("Predicted Class:", pred_class[0])
print(f"P(Y=0|X): {pred_proba[0][0]:.4f}, P(Y=1|X): {pred_proba[0][1]:.4f}")
# 4. Inspect Learned Attributes
print("Class Priors P(Y):", gnb.class_prior_)
print("Learned Feature Means (Theta):")
print(gnb.theta_)
5. sklearn.naive_bayes.MultinomialNB Classifier
Performs text document classification using word frequency counts and Laplace smoothing ().
import numpy as np
from sklearn.naive_bayes import MultinomialNB
# Feature word counts: [count("buy"), count("discount"), count("meeting")]
X_train = np.array([
[4, 3, 0], # Document 1 (Spam)
[3, 2, 1], # Document 2 (Spam)
[0, 1, 4], # Document 3 (Ham)
[1, 0, 5] # Document 4 (Ham)
])
y_train = np.array([1, 1, 0, 0]) # 1: Spam, 0: Ham
# Fit MultinomialNB with Laplace Smoothing alpha=1.0
mnb = MultinomialNB(alpha=1.0)
mnb.fit(X_train, y_train)
# Unseen test document: [2, 1, 0] ("buy", "discount" present)
X_test = np.array([[2, 1, 0]])
pred_label = mnb.predict(X_test)
probabilities = mnb.predict_proba(X_test)
print("Predicted Label (1=Spam, 0=Ham):", pred_label[0])
print("Probabilities [P(Ham|X), P(Spam|X)]:", np.round(probabilities[0], 4))
◇Formulas & Key Equations
Bayes' Theorem & Core Inference
Beta Distribution & Conjugate Updates
Naive Bayes Classification
◇Common Exam Traps
[!WARNING]
Trap 1: Confusing 95% Credible Intervals with 95% Confidence Intervals
- Incorrect Exam Answer: "A 95% Credible Interval means 95% of sample intervals contain the true fixed parameter."
- Correct Exam Answer: "A 95% Credible Interval means there is a 95% probability that the parameter lies within that interval given the observed data."
[!WARNING]
Trap 2: Beta Update Parameter Confusion ( calculation)
- Incorrect: (adding total trials to ).
- Correct: (adding failures/tails to ).
[!WARNING]
Trap 3: Interpreting Beta Hyperparameters vs Pseudo-Counts
- In , the prior pseudo-counts of successes and failures are and .
- For example, a completely uninformative uniform prior over is , which corresponds to 0 prior successes and 0 prior failures!
[!WARNING]
Trap 4: Forgetting to Normalize Discrete Posteriors
- Multiplying prior likelihood gives the unnormalized posterior. To find exact probabilities , you MUST divide each unnormalized value by the sum of all unnormalized values .
[!WARNING]
Trap 5: Misinterpreting the "Naive" Independence Assumption
- Naive Bayes does NOT assume features are independent overall ().
- It assumes features are conditionally independent given the class label ().
[!WARNING]
Trap 6: Missing Laplace Smoothing Zero-Probability Trap
- If an unseen feature count is 0 without smoothing (), , which multiplies the entire class probability to zero regardless of how strong all other feature evidence is.
◇Practice Questions
Q1. Medical Diagnostic Calculation (Bayes' Theorem)
A rare disease affects of a population (). A diagnostic test for the disease has a sensitivity of () and a specificity of ().
A randomly selected patient tests positive (). Calculate the exact posterior probability that the patient actually has the disease.
A) 0.9500 B) 0.0876 C) 0.5000 D) 0.1085
Q2. Beta-Binomial Posterior Parameter & Moments Update
A machine learning engineer models the probability that a web user clicks an ad using a Beta prior . In a test campaign of users, users click the ad.
- Find the posterior distribution parameters and .
- Calculate the exact posterior mean and posterior variance .
A) , , B) , , C) , , D) , ,
Q3. Python Snippet Output Analysis (scipy.stats.beta)
Examine the following Python script:
from scipy.stats import beta
# Prior belief: Beta(4, 4)
a_prior, b_prior = 4, 4
# Observed data: 12 successes out of 16 trials
z, N = 12, 16
# Posterior update
a_post = a_prior + z
b_post = b_prior + (N - z)
mean_val = beta.mean(a_post, b_post)
print(f"a={a_post}, b={b_post}, mean={mean_val:.4f}")
What is the output printed by this program?
A) a=16, b=20, mean=0.4444 B) a=16, b=8, mean=0.6667 C) a=12, b=16, mean=0.4286 D) a=16, b=12, mean=0.5714
Q4. Multinomial Naive Bayes & Laplace Smoothing Calculation
Consider a text classification problem with two classes: Spam () and Ham (). Class Priors: , . Vocabulary size words: "cash", "hello". Training word counts:
Ham: appears 1 time, appears 3 times (Total Ham words = 4).
Spam: appears 3 times, appears 1 time (Total Spam words = 4).
Using Multinomial Naive Bayes with Laplace smoothing , classify a test message (contains 2 instances of and 0 instances of ). Compute .
A) 0.2000 B) 0.5000 C) 0.8000 D) 0.6667
Q5. Python Code Analysis (sklearn.naive_bayes)
Consider the execution of the following scikit-learn code snippet:
import numpy as np
from sklearn.naive_bayes import GaussianNB
X = np.array([[1], [2], [10], [12]])
y = np.array([0, 0, 1, 1])
gnb = GaussianNB()
gnb.fit(X, y)
print("Class Priors:", gnb.class_prior_)
print("Predicted Class for X=6:", gnb.predict([[6]])[0])
What will be displayed for Class Priors and Predicted Class for X=6?
A) Class Priors: [0.5 0.5], Predicted Class for X=6: 0 B) Class Priors: [0.5 0.5], Predicted Class for X=6: 1 C) Class Priors: [0.25 0.75], Predicted Class for X=6: 0 D) Class Priors: [0.5 0.5], Predicted Class for X=6: [0, 1]
◇Answer Key & Step-by-Step Solutions
Q1 Answer: B
Step-by-Step Solution:
- Identify given probabilities:
Sensitivity
Specificity - Apply Law of Total Probability to find marginal evidence :
- Apply Bayes' Theorem:
Q2 Answer: B
Step-by-Step Solution:
- Prior: .
- Data: trials, successes (clicks), and failures (non-clicks).
- Posterior parameters:
Posterior distribution is . - Posterior Mean:
- Posterior Variance:
Q3 Answer: B
Step-by-Step Solution:
- Given prior: .
- Observed: failures.
- Updated parameters:
- Mean of :
- Output string:
a=16, b=8, mean=0.6667.
Q4 Answer: C
Step-by-Step Solution:
- Calculate feature likelihoods with Laplace smoothing ():
Ham Class (, total words ):
Denominator .
.
.
Likelihood .
Unnormalized Posterior .
Spam Class (, total words ):
Denominator .
.
.
Likelihood .
Unnormalized Posterior .
- Normalize probabilities:
Total Evidence .
().
Correct Option is C.
◇References & Navigation
- Previous Topic: ◇Inference for Categorical Data
- Next Topic: ◇Linear Programming
- Related Notes: ◇Inference for Means, ◇Inference for Categorical Data
ACTIVE RECALL VERIFICATION
Select an answer to verify conceptual comprehension and reveal the technical rationale.
In Bayes theorem, what does the prior represent?
Which term describes a prior distribution that, when multiplied by the likelihood, results in a posterior from the same distribution family?
What is the fundamental assumption of the Naive Bayes classifier?
How does the Bayesian approach differ from the Frequentist approach?
The posterior probability is proportional to: